//index.js
var jwxaSwiper = require('../../jwxa/swiper/jwxa-swiper.js');
//获取应用实例
var app = getApp(), $ = app.globalData.$;
Page({
  data: {
    // 热门推荐
    hotList: [],
    // 正在推荐
    liveList: [],
    // 番剧更新
    bangumiList: [],

  },
  onLoad: function () {
    $.init(this);
    jwxaSwiper.initSwiper($, {autoplay: false}, this.swiperChange);

    this.loadBannerData();
    this.loadHotRecommend();
    this.loadRecommendRooms();
    this.loadBangumiRecommend();
  },
  // swiper组件改变事件
  swiperChange: function(event) {
  },
  // 加载Banner图片数据
  loadBannerData: function() {
    $.get('https://api.bilibili.com/x/web-show/res/loc?jsonp=jsonp&pf=7&id=1695', function (res) {
      var items = [];
      res.data.data.forEach(function(value, index, array) {
        var item = {};
        // 测试数据, 偶数项有跳转导航
        (index % 2 == 0) && (item.navigator = {}) && (item.navigator.url = ('../blackboard/blackboard?id=' + value.id));
        item.imgUrl = value.pic;
        items.push(item);
      });
      jwxaSwiper.items(items);
    });
  },
  // 加载热门推荐数据
  loadHotRecommend: function() {
    function __count(val) {
      if (val >= 10000) {
        return (val / 10000).toFixed(1) + '万';
      } else {
        return val;
      }
    }
    $.get('https://www.bilibili.com/index/ranking-3day.json', function (res) {
      var list = res.data.recommend.list, hotList = [];
      for(var r in list) {
        var hotObj = {};
        list.hasOwnProperty(r) && r < 4 &&
        (hotObj.title=list[r].title, hotObj.playNum=__count(list[r].play,
            hotObj.video_review=list[r].video_review,
            hotObj.coverImg=list[r].pic, hotList.push(hotObj)));
      }
      $.data('hotList', hotList);
    });
  },
  // 加载在线直播数据
  loadRecommendRooms: function() {
    $.get('https://live.bilibili.com/h5/recommendRooms', function (res) {
      // 原格式是JSONP,转换成JSON字符串解析
      var data = res.data.substring(1, res.data.length - 2);
      $.data('liveList', $.parseJSON(data).data);
    });
  },
  // 加载番剧数据
  loadBangumiRecommend: function() {
    $.get('https://www.bilibili.com/api_proxy?app=bangumi&action=timeline_v2', function (res) {
      $.data('bangumiList', res.data.list.splice(0, 6));
    });
  },

})
